import {
  BaseCommand,
  cadAppLog,
  cmdInvoker,
  CmdPreChecker,
  ObjInfo,
} from '@amcax/base';
import { cmdCheckTopology } from '@app-base/common/commands/cmd-check-topology';
import { cmdRedo } from '@app-base/common/commands/cmd-redo';
import {
  cmdRenderAllEdge,
  cmdRenderHiddenEdge,
  cmdRenderNoEdge,
  cmdRenderPhysicalMaterial,
  cmdRenderWireframe,
} from '@app-base/common/commands/cmd-renderMode';
import { cmdResizeToArea } from '@app-base/common/commands/cmd-resize-to-area';
import {
  cmdPanView,
  cmdRotateView,
  cmdZoomView,
} from '@app-base/common/commands/cmd-toolbar-mouse-control';
import { cmdUndo } from '@app-base/common/commands/cmd-undo';
import {
  cmdBackView,
  cmdBottomView,
  cmdFrontView,
  cmdIsometricView,
  cmdLeftView,
  cmdRightView,
  cmdTopView,
  cmdVerticalView,
} from '@app-base/common/commands/cmd-view-classification';
import { cmdFitView } from '@app-base/environments/nextcad/commands/feature/cmd-fit-view';
import { cmdProject3D } from '@app-base/environments/nextcad/commands/sketch/cmd-project-3d';
import { cmdIntersect3D } from '@app-cad-env/nextcad/commands/sketch/cmd-intersect-3d';
import { cmdSketchOut } from '@app-cad-env/nextcad/commands/sketch/cmd-sketch-out';
import { eventCenterManager } from '@app-cad/common/events/EventCenterManager';
import { cmdSketchIn } from '@app-cad/environments/nextcad/commands/feature/cmd-sketch-in';

export const sketchPreChecker: CmdPreChecker = async (
  cmd: BaseCommand,
  props: ObjInfo,
) => {
  cadAppLog('[debug]sketchPreChecker', cmd, props);

  if (cmd.group === 'sketch') {
    // 草图命令，判断当前是否在草图编辑模式
    // 如果不是，需要进入草图模式（选择平面或者某个草图）
    // 选择好后，返回true
    // 如果用户取消选择，返回false
    const excludedCurrentCmdIds = [cmdIntersect3D.id, cmdProject3D.id];

    if (
      !eventCenterManager.isSketchMode &&
      !excludedCurrentCmdIds.includes(cmdInvoker.currentCmd?.id)
    ) {
      return await cmdInvoker.invokeCmd(cmdSketchIn, null, {
        skipCameraChange: true,
      });
    }
  } else {
    // 非草图命令，判断当前是否在草图编辑模式
    // 如果是，退出草图编辑模式，返回true
    // 如果不是，返回false
    // 空白草图点击撤销会有单独的退出方法
    const excludedCmdIds = [
      cmdUndo.id,
      cmdRedo.id,
      cmdSketchOut.id,
      cmdCheckTopology.id,
      cmdBackView.id,
      cmdBottomView.id,
      cmdFrontView.id,
      cmdIsometricView.id,
      cmdLeftView.id,
      cmdRightView.id,
      cmdTopView.id,
      cmdVerticalView.id,
      cmdPanView.id,
      cmdRotateView.id,
      cmdZoomView.id,
      cmdRenderAllEdge.id,
      cmdRenderHiddenEdge.id,
      cmdRenderNoEdge.id,
      cmdRenderWireframe.id,
      cmdRenderPhysicalMaterial.id,
      cmdFitView.id,
      cmdResizeToArea.id,
    ];

    if (!excludedCmdIds.includes(cmd.id) && eventCenterManager.isSketchMode) {
      await cmdInvoker.invokeCmd(cmdSketchOut);
      return true;
    }
  }

  return true;
};
